<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    class="full_screen_dialog "
    width="95%"
    :visible.sync="visible"
  >
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="80px" @keyup.enter.native="dataFormSubmit()">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="LOGO" prop="brandimg">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              :on-success="handleAvatarSuccess"
              :action="uploadUrl"
              :with-credentials="true"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="dataForm.brandimg" :src="dataForm.brandimgFullPath" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-col>
        <!--列表详细-->
        <el-col :span="20">
          <el-form-item label="品牌名称" prop="brandname">
            <el-input v-model="dataForm.brandname" placeholder="" />
          </el-form-item>
          <el-form-item label="排序号" prop="sortno">
            <el-input v-model="dataForm.sortno" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="所属分类" prop="cats">
            <el-cascader
              v-model="dataForm.cats"
              style="width: 100%"
              clearable
              :props="props"
              :options="options"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="品牌描述" prop="branddesc">
            <vue-ueditor-wrap v-model="dataForm.branddesc" :config="myConfig" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col style="text-align: right;">
        <el-button size="mini" icon="el-icon-close" @click="visible = false">取消</el-button>
        <el-button size="mini" icon="el-icon-check" type="primary" @click="dataFormSubmit()">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import VueUeditorWrap from 'vue-ueditor-wrap' // ES6 Modul
import { treeDataTranslate } from '@/utils'
export default {
  components: {
    VueUeditorWrap
  },
  data() {
    return {
      visible: false,
      cats: [],
      props: { multiple: true },
      uploadUrl: this.$http.adornUrl(`/system/file/uploadBrands`),
      dataForm: {
        brandid: 0,
        brandname: '',
        brandimg: '',
        branddesc: '',
        createtime: '',
        dataflag: '',
        sortno: '',
        brandimgFullPath: '',
        cats: []
      },
      options: [],
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 170,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: '/static/plugins/ueditor-1.4.3.3/'
      },
      dataRule: {
        brandname: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        brandimg: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        branddesc: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        createtime: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        dataflag: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        sortno: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(id) {
      // this.$cats({'parentId': 0}, this.cats);
      this.dataForm.brandid = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm.cats = []
        // 商品目录
        this.$http({
          url: this.$http.adornUrl('/goods/cats/dorpdownlist'),
          method: 'get',
          params: this.$http.adornParams({
            'parentId': 0
          })
        }).then(({ data }) => {
          if (data && data.list != null && data.list.length > 0) {
            var lst = []
            for (var i = 0; i < data.list.length; i++) {
              lst.push({
                value: data.list[i].catid,
                parentid: data.list[i].parentid,
                label: data.list[i].catname
              })
            }
            this.options = treeDataTranslate(lst, 'value', 'parentid')
          }
          if (this.dataForm.brandid) {
            this.$http({
              url: this.$http.adornUrl(`/commodit/brands/info/${this.dataForm.brandid}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.brandname = data.brands.brandname
                this.dataForm.brandimg = data.brands.brandimg
                this.dataForm.branddesc = data.brands.branddesc
                this.dataForm.createtime = data.brands.createtime
                this.dataForm.dataflag = data.brands.dataflag
                this.dataForm.sortno = data.brands.sortno
                const attrCats = data.brands.cats
                if (attrCats) {
                  const cats = []
                  attrCats.forEach((data, index) => {
                    cats.push(data.split('__'))
                  })
                  this.dataForm.cats = cats
                }
                if (this.dataForm.brandimg) {
                  this.dataForm.brandimgFullPath = this.$http.adornUrl(`/system/file/downloadBrands/${this.dataForm.brandimg}`)
                }
              }
            })
          }
        })
      })
    },
    handleChange(val) {
      console.log(val)
    },
    // 表单提交
    dataFormSubmit() {
      const _this = this
      this.$refs['dataForm'].validate((valid) => {
        const cats = []
        if (_this.dataForm.cats) {
          _this.dataForm.cats.forEach((value, index) => {
            if (value) {
              cats.push(value.join('__'))
            }
          })
        }
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/commodit/brands/${!this.dataForm.brandid ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'brandid': this.dataForm.brandid || undefined,
              'brandname': this.dataForm.brandname,
              'brandimg': this.dataForm.brandimg,
              'branddesc': this.dataForm.branddesc,
              'createtime': this.dataForm.createtime,
              'dataflag': this.dataForm.dataflag,
              'sortno': this.dataForm.sortno,
              'cats': cats
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },

    handleAvatarSuccess(response, file, fileList) {
      if (response.code === 0 && response.file) {
        this.dataForm.brandimg = response.file.sysFileEncryptionName
        this.dataForm.brandimgFullPath = this.$http.adornUrl(`/system/file/downloadBrands/${response.file.sysFileEncryptionName}`)
        // this.dataForm.brandimg = this.$http.adornUrl(`/system/file/downloadBrands/${response.file.sysFileEncryptionName}`)
      } else {
        this.$message.error(response.msg)
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style>
  .edui-button {
    line-height: 20px !important
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
